﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Web.UI;
using KPIS.GERP.GBMS.APP_UI.Common;
using KPIS.GERP.GBMS.IBLL;
using KPIS.GERP.GBMS.BLL;
using KPIS.GERP.GBMS.MODEL;
//using Telerik.Reporting;
using Telerik.Web.UI;

namespace KPIS.GERP.GBMS.APP_UI.Form
{
    public partial class Bgm_Kpi_List : System.Web.UI.Page
    {
        IBgmKpiListBLL KpiLis = new BgmKpiListBLL();
        IStrategyDataMappingBLL strategyDataMappingBLL = new StrategyDataMappingBLL();
        IProject projectBLL = new Project_BLL();
        Main main = new Main();
        private SsMng creatby = new SsMng();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                lblBgmYear.Text = Request.QueryString["year"];
                lblBgmStratMapSeq.Text = Request.QueryString["seq"];
                lblType.Text = Request.QueryString["type"];
                int? intStatMapSeq = main.ConvertNullInt(Request.QueryString["seq"]);
                string strType = lblType.Text;

                string checkNameKpiTarget = "";
                if (lblType.Text == "2")
                {
                     checkNameKpiTarget = KpiLis.CheckNameKpiTarget(intStatMapSeq, strType);
                }
                else if (lblType.Text == "rq")
                {
                     checkNameKpiTarget = KpiLis.CheckNameKpiTarget(intStatMapSeq, strType);
                }
                else if (lblType.Text == "pj")
                {
                     checkNameKpiTarget = KpiLis.CheckNameKpiTarget(intStatMapSeq, strType);
                }
                lblKpiName.Text = "รายงานตัวชี้วัดความสำเร็จของ" + checkNameKpiTarget;

                ddlKpiType.DataSource = KpiLis.LoadKpiType();
                ddlKpiType.DataBind();
                ddlKpiType.Items.Insert(0, new RadComboBoxItem("กรุณาเลือกประเภทตัวชี้วัด", ""));

                ddlKpiTarget.DataSource = KpiLis.LoadKpiTarget();
                ddlKpiTarget.DataBind();
                ddlKpiTarget.Items.Insert(0, new RadComboBoxItem("กรุณาเลือกเป้าหมายตัวชี้วัด", ""));

                ChangeMode(Main.EditMode.View);
            }
        }

        private void LoadGtgKpiCtrl()
        {
            string strStatMap = Request.QueryString["Seq"];
            string strBgmYear = Request.QueryString["year"];
            string strType = lblType.Text;
            string strKpiSeq = lblkpiSeq.Text;

            dtgKpiCtrl.DataSource = KpiLis.Search(main.ConvertNullInt(strStatMap), main.ConvertNullInt(strBgmYear), null, null, null, null, strType);
            dtgKpiCtrl.DataBind();

            ChangeMode(Main.EditMode.View);
        }

        protected void dtgKpiCtrl_ItemCommand(object sender, GridCommandEventArgs e)
        {
            string strCommandName = e.CommandName;

            if (strCommandName == "GridEdit")
            {
                CheckLabelName();
                ChangeMode(Main.EditMode.Edit);

                GridDataItem item = (GridDataItem) e.Item;

                lblkpiSeq.Text = main.WebString(item["kpi_seq"].Text);
                txtKpiName.Text = main.WebString(item["kpi_name"].Text);
                txtDes.Text = item["description"].Text;
                txtKpiUnit.Text = main.WebString(item["kpi_unit"].Text);
                ddlKpiType.SelectedValue = main.WebString(item["kpi_type_seq"].Text);
                ddlKpiTarget.SelectedValue = main.WebString(item["target_seq"].Text);
                txtKpiWeight.Text = main.WebString(item["weight"].Text);
                lblKpiTargetSeq.Text = main.WebString(item["kpi_det_seq"].Text);
                string strKpiSeq = main.WebString(item["kpi_seq"].Text);

                DataTable dtb = KpiLis.SearchTarget(strKpiSeq);
                RadGrid1.DataSource = dtb;
                RadGrid1.DataBind();
            }
            else if (strCommandName == "ViewDetail")
            {
                GridDataItem item = (GridDataItem)e.Item;
            }
            else if (strCommandName == "GridDelete")
            {
                GridDataItem item = (GridDataItem)e.Item;

                string strKpiSeq = main.WebString(item["kpi_seq"].Text);
                KpiLis.Delete(strKpiSeq, creatby.EmpSeq);
                KpiLis.DeleteTarget(strKpiSeq, creatby.EmpSeq);

                LoadGtgKpiCtrl();
            }
        }

        protected void dtgKpiCtrl_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            string strStatMap = Request.QueryString["Seq"];
            string strBgmYear = Request.QueryString["year"];
            string strType = lblType.Text;

            dtgKpiCtrl.DataSource = KpiLis.Search(main.ConvertNullInt(strStatMap), main.ConvertNullInt(strBgmYear), null, null, null, null, strType);

            ChangeMode(Main.EditMode.View);
        }

        private void ChangeMode(Main.EditMode mode)
        {
            switch (mode)
            {
                case Main.EditMode.AddNew:

                    dtgKpiCtrl.Visible = false;
                    pnlInfo.Visible = true;
                    pnlTarget.Visible = true;
                    ShowGrid.Visible = true;
                    AddNew.Visible = true;
                    Save_AddNew.Visible = true;
                    pnlLoadGrid.Visible = false;
                    Delete.Visible = false;
                    Save_Edit.Visible = false;
                    ddlKpiType.Enabled = true;
                    ddlKpiTarget.Enabled = true;
                    RadGrid1.Visible = true;
                    DeleteEdit.Visible = false;
                   
                break;

                case Main.EditMode.View:

                    dtgKpiCtrl.Visible = true;
                    pnlInfo.Visible = false;
                    pnlTarget.Visible = false;
                    ShowGrid.Visible = true;
                    AddNew.Visible = true;
                    Save_AddNew.Visible = false;
                    pnlLoadGrid.Visible = true;
                    Delete.Visible = true;
                    Save_Edit.Visible = false;
                    ddlKpiTarget.Enabled = false;
                    RadGrid1.Visible = false;
                    DeleteEdit.Visible = false;

                break;
                    
                case Main.EditMode.Edit :

                    dtgKpiCtrl.Visible = false;
                    pnlInfo.Visible = true;
                    pnlTarget.Visible = true;
                    ShowGrid.Visible = true;
                    AddNew.Visible = false;
                    pnlLoadGrid.Visible = false;
                    Delete.Visible = false;
                    Save_Edit.Visible = true;
                    ddlKpiType.Enabled = true;
                    ddlKpiTarget.Enabled = false;
                    RadGrid1.Visible = true;
                    DeleteEdit.Visible = true;

                 break;
            }
        }

        private bool CheckNullValue()
        {
            bool bOk = true;
            string strKpiName = txtKpiName.Text;
            string strKpiType = ddlKpiType.SelectedValue;
            string strKpiUnit = txtKpiUnit.Text;
            string strKpiWeight = txtKpiWeight.Text;

            if(strKpiName.Length == 0)
            {
                main.MessageAlert(Page, "กรุณากรอกชื่อตัวชี้วัด");
                bOk = false;
            }
            else if (strKpiType.Length == 0)
            {
                main.MessageAlert(Page, "กรุณากรอกประเภทตัวชี้วัด");
                bOk = false;
            }
            else if (strKpiUnit.Length == 0)
            {
                main.MessageAlert(Page, "กรุณากรอกหน่วยวัด");
                bOk = false;
            }
            else if (ddlKpiTarget.SelectedValue.Length == 0)
            {
                main.MessageAlert(Page, "กรุณาเลือกเป้าหมายตัวชี้วัด"); 
                bOk = false;
            }
            return  bOk;
        }

        private  bool CheckTargetValue()
        {
           bool CheckTargetValue = false;

            for (int i = 0; i < RadGrid1.Items.Count; i++ )
           {
               RadNumericTextBox txtRadScore = (RadNumericTextBox) RadGrid1.Items[i]["Score"].FindControl("txtRadScore");
               if (txtRadScore.Value > 0)
               {
                   CheckTargetValue = true;
                   return CheckTargetValue;
               }
           }
            return CheckTargetValue;
        }

        private void LoadGrid(string kpiTp)
        {
            var data = KpiLis.LoadGridKpiTarget(kpiTp);
            RadGrid1.DataSource = data; 
            RadGrid1.DataBind();

        }

        protected void ddlKpiTarget_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadGrid(ddlKpiTarget.SelectedValue);
        }

        private void ClearControlData()
        {
            txtKpiName.Text = "";
            txtDes.Text = "";
            txtKpiUnit.Text = "";
            txtKpiWeight.Text = "";
            ddlKpiType.SelectedIndex = 0;
            ddlKpiTarget.SelectedIndex = 0;
        }

        private void CheckLabelName()
        {
            int? intStatList = main.ConvertNullInt(Request.QueryString["Seq"]);
            string strType = lblType.Text;

            string checkNameKpiTarget = "";
            if (lblType.Text == "2")
            {
                checkNameKpiTarget = KpiLis.CheckNameKpiTarget(intStatList, strType);
            }
            else if (lblType.Text == "rq")
            {
                checkNameKpiTarget = KpiLis.CheckNameKpiTarget(intStatList, strType);
            }
            else if (lblType.Text == "pj")
            {
                checkNameKpiTarget = KpiLis.CheckNameKpiTarget(intStatList, strType);
            }
            lblKpiTargetName.Text = "รายละเอียดตัวชี้วัดความสำเร็จของ" + checkNameKpiTarget;
        }

        protected void Save_AddNew_Click(object sender, EventArgs e)
        {
            string strKpiTarget = ddlKpiTarget.SelectedValue;

            if (!CheckNullValue())
            {
                RadGrid1.DataSource = KpiLis.LoadGridKpiTarget(strKpiTarget);
                RadGrid1.DataBind();
                return;
            }

            if (!CheckTargetValue())
            {
                RadGrid1.DataSource = KpiLis.LoadGridKpiTarget(strKpiTarget);
                RadGrid1.DataBind();
                main.MessageAlert(Page, "กรอกผลการชี้วัดอย่างน้อย 1 ตัว");
                return;
            }

            string strBgmKpiSeq = "";
            string strKpiSeq = "";
            string strKpiName = txtKpiName.Text;
            string strDes= txtDes.Text;
            string strKpiType = ddlKpiType.SelectedValue;
            //string strKpiTarget = ddlKpiTarget.SelectedValue;
            string strKpiUnit = txtKpiUnit.Text;
            int? intKpiWeight = main.ConvertNullInt(txtKpiWeight.Text);
            int intTargetSeq = Convert.ToInt32(ddlKpiTarget.SelectedValue);
            int intKpiYear = Convert.ToInt32(Request.QueryString["year"]);
            string strStatMapping = Request.QueryString["Seq"];
            int intStatMapping = Convert.ToInt32(Request.QueryString["Seq"]);
            string strType = lblType.Text;
            string strStratListSeq = null;
            string strKpiListTypeSeq = null;
            
            CheckLabelName();

            bool CheckValue = KpiLis.CheckValue(strKpiSeq);

            if (CheckValue == true)
            {
                if (strType == "2")
                {
                    List<StrategyDataMappingInfo> strategyDataMappingInfoList = (List<StrategyDataMappingInfo>)strategyDataMappingBLL.Search(strStatMapping
                            , "", "", "", "", "");
                    strStratListSeq = strategyDataMappingInfoList[0].Sequence.ToString();
                    strKpiListTypeSeq = strategyDataMappingInfoList[0].DataList.StrategyType.Sequence.ToString();


                    strBgmKpiSeq = KpiLis.Insert(intStatMapping, intTargetSeq, intKpiYear, creatby.EmpSeqI
                                                , strKpiName, strDes, strKpiType, strKpiUnit, intKpiWeight
                                                , strType);
                }
                else if (strType == "rq" || strType == "pj")
                {
                    //strStratListSeq = intStatMapping;

                    strBgmKpiSeq = KpiLis.Insert(intStatMapping, intTargetSeq, intKpiYear, creatby.EmpSeqI,
                                                 strKpiName, strDes, strKpiType, strKpiUnit, intKpiWeight, strType);
                }

                var score =  new  Dictionary<int, double?>();

                foreach (GridDataItem item in RadGrid1.Items)
                {
                    var txtRadTargetSeq = (RadTextBox)item["TargetID"].FindControl("txtRadTargetSeq");
                    var txtRadScore = (RadNumericTextBox)item["Score"].FindControl("txtRadScore");

                    score.Add(Convert.ToInt32(txtRadTargetSeq.Text), (main.ConvertNullDouble(txtRadScore.Value)));
                }

                InsertTarget(strBgmKpiSeq, strStatMapping, score, creatby.EmpSeq);

                ClearControlData();
                LoadGtgKpiCtrl();
                ChangeMode(Main.EditMode.View);
                
                main.MessageAlert(Page, "บันทึกข้อมูลเรียบร้อยแล้ว");
            }
            else
            {
                main.MessageAlert(Page, "กรุณาตรวจสอบข้อมูลอีกครั้ง");
            }

      }

        private void InsertTarget(string strBgmKpiSeq, string strStatMapping, Dictionary<int, double?> scores, string created_by)
        {
            KpiLis.InsertTarget(strBgmKpiSeq, strStatMapping, scores, created_by);
        }

        protected void ShowGrid_Click(object sender, EventArgs e)
        {
            string strStatMapping = Request.QueryString["Seq"];
            string strBgmYear = Request.QueryString["year"];
            string strType = lblType.Text;

            dtgKpiCtrl.DataSource = KpiLis.Search(main.ConvertNullInt(strStatMapping), main.ConvertNullInt(strBgmYear), null, null, null, null, strType);

            ChangeMode(Main.EditMode.View);
        }

        protected void Cancel_Click(object sender, EventArgs e)
        {
            ClearControlData();
            ChangeMode(Main.EditMode.View);
        }

        protected void AddNew_Click(object sender, EventArgs e)
        {
            CheckLabelName();
            ClearControlData();
            ChangeMode(Main.EditMode.AddNew);
            LoadGrid(ddlKpiTarget.SelectedValue);
        }

        protected void Save_Edit_Click(object sender, EventArgs e)
        {
            string strBgmKpiSeq = "";
            string strKpiName = txtKpiName.Text;
            string strDes = txtDes.Text;
            string strKpiType = ddlKpiType.SelectedValue;
            string strKpiUnit = txtKpiUnit.Text;
            string strKpiWeight = txtKpiWeight.Text;
            string strType = lblType.Text;
            string strStatMapping = Request.QueryString["Seq"];
            string strKpiSeq = lblkpiSeq.Text;
            string strKpiTarget = ddlKpiTarget.SelectedValue;
            string strStratListSeq = null;
            string strKpiListTypeSeq = null;

            CheckLabelName();

            if (!CheckNullValue())
            {
                RadGrid1.DataSource = KpiLis.SearchTarget(strKpiSeq);
                RadGrid1.DataBind();
                return;
            }

            if (!CheckTargetValue())
            {
                RadGrid1.DataSource = KpiLis.SearchTarget(strKpiSeq);
                RadGrid1.DataBind();
                main.MessageAlert(Page, "กรอกผลการชี้วัดอย่างน้อย 1 ตัว");
                return;
            }

            bool CheckValue = KpiLis.CheckValue(strKpiSeq);

            if(CheckValue == true)
            {
                KpiLis.Update(strKpiSeq, strKpiName, strDes, strKpiUnit, strKpiType, strKpiWeight, creatby.EmpSeq, strType);
   
                var score = new Dictionary<int, double?>();
                string strKpiDetSeq = string.Empty;
                foreach (GridDataItem item in RadGrid1.Items)
                {
                    strKpiDetSeq = main.WebString(item["kpi_det_seq"].Text);
                    var dblScore = (RadNumericTextBox)item["Score"].FindControl("txtRadScore");

                    UpdateTarget(strKpiDetSeq, main.ConvertNullDouble(dblScore.Text), creatby.EmpSeq);

                    RadGrid1.DataSource = KpiLis.SearchTarget(strKpiSeq);
                    RadGrid1.DataBind();
                }

                LoadGtgKpiCtrl();
                ClearControlData();
                ChangeMode(Main.EditMode.View);

                main.MessageAlert(Page, "แก้ไขข้อมูลเรียบร้อยแล้ว");
            }
            else
            {
                RadGrid1.DataSource = KpiLis.SearchTarget(strKpiSeq);
                RadGrid1.DataBind();
                main.MessageAlert(Page, "กรุณาตรวจสอบข้อมูลอีกครั้ง");
            }
        }

        protected void Delete_Click(object sender, EventArgs e)
        {
            if (pnlLoadGrid.Visible == true)
            {
                foreach(GridDataItem item in dtgKpiCtrl.SelectedItems)
                {
                    string strKpiSeq = main.WebString(item["kpi_seq"].Text);
                    KpiLis.Delete(strKpiSeq, creatby.EmpSeq);
                    KpiLis.DeleteTarget(strKpiSeq, creatby.EmpSeq);
                }
            }

            LoadGtgKpiCtrl();
            ChangeMode(Main.EditMode.View);
        }

        private void UpdateTarget(string strKpiDetSeq, double? dblKpiDetTarget, string created_by)
        {
            KpiLis.UpdateTarget(strKpiDetSeq, dblKpiDetTarget, created_by);
        }

        private void DeleteTarget(string strKpiSeq, string created_by)
        {
            KpiLis.DeleteTarget(strKpiSeq, created_by);
        }

        protected void DeleteEdit_Click(object sender, EventArgs e)
        {
            string strKpiSeq = lblkpiSeq.Text;

            KpiLis.Delete(strKpiSeq, creatby.EmpSeq);
            KpiLis.DeleteTarget(strKpiSeq, creatby.EmpSeq);

            LoadGtgKpiCtrl();
            ChangeMode(Main.EditMode.View);
        }
   }
}
